import { login, logout} from '@/api/user'
import { getToken1, setToken1, removeToken1,getToken2, setToken2, removeToken2 } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    accessToken: getToken1(),
    refreshToken:getToken2(),
    token:getToken1(),
    name: '',
    avatar: '',
    button:[],
    page:[],
    status:''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_BUTTON: (state, buttons) => {
    state.button = buttons
  },
  SET_PAGE: (state, pages) => {
    state.page = pages
  },
  SET_TOKEN1: (state, token) => {
    state.accessToken = token
  },
  SET_TOKEN2: (state, token) => {
    state.refreshToken = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_STATUS: (state, status) => {
    state.status = status
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const data = response
        commit('SET_TOKEN1', data.accessToken)
        commit('SET_TOKEN2', data.refreshToken)
        commit('SET_PAGE',data.data.menu) 
       localStorage.setItem('page',JSON.stringify(data.data.menu))
        commit('SET_BUTTON',data.data.control)
        setToken1(data.accessToken)
        setToken2(data.refreshToken)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

   // get user info
//  login({ commit, state }) {
//     return new Promise((resolve, reject) => {
//       login(state.token).then(response => {
//         console.log(response)
//         const { data } = response
      
//         if (!data) {
//           return reject('Verification failed, please Login again.')
//         }

//         const { name, avatar } = data

//         commit('SET_NAME', name)
//         commit('SET_AVATAR', avatar)
//         resolve(data)
//       }).catch(error => {
//         reject(error)
//       })
//     })
//   },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken1()
        removeToken2() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken1()
      removeToken2() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

